package com.idroid.activities;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.idroid.R;
import com.idroid.dialogs.HelpDialog;
import com.idroid.domain.LocationTracker;
import com.idroid.domain.ParkingArea;
import com.idroid.domain.SearchType;
import com.idroid.domain.SerializableLocation;
import com.idroid.fragments.MapFragment;

/**
 * Displays a list of contacts.
 * 
 */
public class ParkingListActivity extends ListActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);

		final Bundle extra = getIntent().getExtras();

		final List<ParkingArea> areas = (List<ParkingArea>) extra
				.getSerializable("parkingAreas");
	
		
		final SerializableLocation startingLocation = (SerializableLocation) extra.getSerializable("startingLoc");
		

		Thread t = new Thread(new Runnable() {

			public void run() {
				for (ParkingArea area : areas) {
					LocationTracker locationTracker = null;
					try {
						locationTracker = LocationTracker.getInstance();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (!area.getHasPosition()) {

						locationTracker.setAreaPosition(
								ParkingListActivity.this, area);

					}
				}

			}
		});

		t.start();
		SearchType searchType = (SearchType) extra
				.getSerializable("searchType");

		ToolbarConfig toolbarConfig = new ToolbarConfig(this,
				searchType.getDescription());

		Button helpButton = toolbarConfig.getToolbarHelpButton();
		helpButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				HelpDialog dialog = HelpDialog
						.newInstance(
								ParkingListActivity.this,
								"Parking List Help",
								"This page lists the parking areas based on the query requested and ordered by the area's distance from the user.  Selecting an area will bring up more information.  If the distance is set to N/A please retry.");
				dialog.show(ParkingListActivity.this.getFragmentManager(),
						"parkinglisthelp");

			}
		});

		// initialize the list view
		setListAdapter(new ParkingAreaAdapter(this, R.layout.list_item, areas));
		ListView lv = getListView();
		// lv.setTextFilterEnabled(true);

		// handle the item click events
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent i = new Intent(ParkingListActivity.this,
						ParkingDetailActivity.class);
				i.putExtra("parkingArea",
						((ParkingAreaAdapter) getListAdapter())
								.getItem(position));
//				System.out.println("STARTING LOC "+startingLocation);
				i.putExtra("startingLoc", (Serializable)startingLocation);
				i.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);

				startActivity(i);

				// When clicked, show a toast with the TextView text
				/*
				 * Toast.makeText(getApplicationContext(), "Clicked: " +
				 * ((ParkingAdapter)getListAdapter()).getItem(position).getId(),
				 * Toast.LENGTH_SHORT).show();
				 */
			}
		});

		Intent i = new Intent();
		i.putExtra("showsearch", true);

		this.setResult(1, i);

	}

	/*
	 * We need to provide a custom adapter in order to use a custom list item
	 * view.
	 */
	public class ParkingAreaAdapter extends ArrayAdapter<ParkingArea> {

		public ParkingAreaAdapter(Context context, int textViewResourceId,
				List<ParkingArea> objects) {
			super(context, textViewResourceId, objects);

		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			if (row == null) {

				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.list_item, parent, false);
			}

			ParkingArea parking = getItem(position);

			if (Float.compare(parking.getDistanceFromUserInMiles(),
					Float.MAX_VALUE) == 0) {
				((TextView) row.findViewById(R.id.item_distance))
						.setText("N/A");
			} else {
				DecimalFormat myFormatter = new DecimalFormat("###,###,###.###");
				String output = myFormatter.format(parking
						.getDistanceFromUserInMiles());

				// distance needs to be calculated
				((TextView) row.findViewById(R.id.item_distance))
						.setText(output + " Miles");
			}

			((TextView) row.findViewById(R.id.item_name)).setText(parking
					.getAreaName().trim());
			((TextView) row.findViewById(R.id.item_rate)).setText(parking
					.getFormattedHourlyRate().trim());
			return row;

		}
	}

}
